#include <iostream>
#include <sstream>
#include <vector>
#include <string>
#include <memory>
#include <jsoncpp/json/json.h>

bool serialize(const Json::Value &root, std::string &str)
{
    Json::StreamWriterBuilder swb;
    std::shared_ptr<Json::StreamWriter> sw(swb.newStreamWriter());
    std::stringstream ss;
    int ret = sw->write(root, &ss);
    if (ret != 0)
    {
        std::cout << "json serialize failed!! \n";
        return false;
    }
    str = ss.str();
    return true;
}

bool unserialize(const std::string &str, Json::Value& root)
{
    Json::CharReaderBuilder crb;
    std::shared_ptr<Json::CharReader> cr(crb.newCharReader());
    std::string err;
    bool ret = cr->parse(str.c_str(), str.c_str() + str.size(), &root, &err);
    if (ret == 0)
    {
        std::cout << "json unserialize failed: " << err << std::endl;
        return false;
    }
    return true;
}

int main()
{
    Json::Value root;

    root["姓名"] = "小明";
    root["年纪"] = 18;
    root["成绩"].append(98);
    root["成绩"].append(88.8);
    root["成绩"].append(77.7);
    std::string str;
    serialize(root, str);
    std::cout << str << std::endl;

    Json::Value root1;
    unserialize(str, root1);
    std::cout << "-------------" << std::endl;
    std::cout << root1["姓名"].asString() << std::endl;
    std::cout << "-------------" << std::endl;
    std::cout << root1["年纪"].asInt() << std::endl;
    std::cout << "-------------" << std::endl;
    int sz = root1["成绩"].size();
    for (int i = 0; i < sz; i++)
    {
        std::cout << root1["成绩"][i].asFloat() << std::endl;
    }
    return 0;
}